<?php
$loader->requireOnce('/includes/Datasource_sql.class.php');

/**
 * A datasource of all of the users of the system.
 */
class User_DS extends Datasource_sql 
{
	/**#@+
	 * @access private
	 */
	var $_internalName = 'User_DS';
	var $_type = 'html';
	var $_typeCache = array();	
	/**##@-*/
	/**
	 * @author hdviet
	 * update for localize demography
	 */
	
	/**
	 * Handle instantiation
	 */
	function User_DS($deptId = 0, $roleGroupId = 0, $enable = 'all') {					
		$db =& Celini::dbInstance();
		$sql = array(
				'cols' => "
					e.person_id,
					e.name personname,					
					e.email,
					e.phone_number,					
					u.username, u.user_id, u.enable",
				'from' => "
					employee AS e
					INNER JOIN user AS u ON e.person_id = u.person_id",
				'where' => "username != 'admin'"
			); 
			
		if ($deptId > 0) {
		    $sql['where'] .= " AND e.department_id = $deptId";
		}	
		if ($enable != 'all') {
		    $sql['where'] .= " AND u.enable = $enable";
		}
		if ($roleGroupId > 0) {
		    $groups =$GLOBALS['security']->get_group_objects($roleGroupId);
            if (empty($groups['users'])) {
                $sql['where'] .= " AND false";
            } else {
                $sql['where'] .= " AND ( false ";
                foreach ($groups['users'] as $accountName) {
                    $sql['where'] .= "OR u.username = '$accountName'";
                }
                $sql['where'] .= " )";                  
            }		    		    		    		     
		}
		
			
		$this->setup(
			$db,
			$sql,
			array(
				'personname' => 'Name',
				'username' => 'Username',				
				'email'	=> 'Email',
				'phone_number' => 'Phone Number',
				'enable'	=> 'Enable' 
			)
		);
		
		$this->registerFilter('personname', array(&$this, '_actionEditLink'));
	}
	
	
	/**
	 * Looks up person type enum value
	 *
	 * @param  string
	 * @return string
	 * @access private
	 */
	function _lookupType($value) {
		if (!isset($this->_typeCache[$value])) {
			$em =& Celini::enumManagerInstance();
			$this->_typeCache[$value] = $em->lookup('person_type', $value);
		}
		return $this->_typeCache[$value];
	}
	
	
	/**
	 * Formats link to edit a given user
	 *
	 * @param  string
	 * @return return
	 * @access private
	 */
	function _actionEditLink($value, $rowValues) {
		$id=$rowValues['person_id'];
		return "<a href=\"" . "javascript:loadPage('userManagementContent', 'Edit', $id);" . "\">$value</a>";
	}
}

?>
